package com.spring.demo.spring_boot;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.spring.demo.spring_boot.domain.Role;
import com.spring.demo.spring_boot.domain.UserInfo;
import com.spring.demo.spring_boot.service.SecurityService;

/**
 * 
 * @author 王辉阳
 * @date 2017年8月15日 下午1:59:19
 * @description spring security的认证管理的提供者
 */
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
	private static final Logger logger = LogManager.getLogger(CustomAuthenticationProvider.class);

	@Autowired
	private SecurityService securityService;

	/**
	 * spring security 认证管理
	 */
	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		String loginName = authentication.getName();
		String password = authentication.getCredentials().toString();
		List<GrantedAuthority> grantedAuths = new ArrayList<>();
		if (vaildateUser(loginName, password, grantedAuths)) {
			Authentication auth = new UsernamePasswordAuthenticationToken(loginName, password, grantedAuths);
			return auth;
		} else {
			return null;
		}
	}

	/**
	 * 验证登录条件
	 * 
	 * @param loginName
	 * @param password
	 * @param grantedAuths
	 * @return
	 */
	public boolean vaildateUser(String loginName, String password, List<GrantedAuthority> grantedAuths) {
		UserInfo user = securityService.findByName(loginName);
		if (user == null || loginName == null || password == null) {
			return false;
		}
		if (user.getPassword().equals(password)) {
			// 存放所有角色
			Set<Role> roles = securityService.rolesOfUser(user.getUserId());
			for (Role role : roles) {
				grantedAuths.add(new SimpleGrantedAuthority(role.getName()));
			}

			return true;
		}
		return false;
	}

	@Override
	public boolean supports(Class<?> authentication) {
		return authentication.equals(UsernamePasswordAuthenticationToken.class);
	}
}
